package org.datascooter.extension;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

public class AloneFileChecker {

	private static final String FILE_NAME = "/";
	private static final String SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN = "***Second instances are progibited - application will shutdowned.";
	private static final String APP_LOCK = "app.lock";
	private static String lockPath;
	private static File file;

	public static void checkAlone() throws SecondInstanceException {
		try {
			lockPath = EclipsePathResolver.resolvePath(APP_LOCK);
			if (lockPath != null) {
				file = new File(lockPath);
				if (file.exists()) {
					Logger.getLogger(AloneFileChecker.class.getName()).severe(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN);
					throw new SecondInstanceException(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN);
				}
			} else {
				lockPath = EclipsePathResolver.resolvePath(FILE_NAME);
				file = new File(lockPath, APP_LOCK);
				file.createNewFile();
				file.deleteOnExit();
				Runtime.getRuntime().addShutdownHook(new Thread() {

					public void run() {
						if (file.exists()) {
							file.delete();
						}
					}
				});
			}
		} catch (IOException e) {
			throw new SecondInstanceException(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN, e);
		}
	}
}
